<template>
  <div class="physical-exam-page" style="padding: 20px; background: #f5f7fa; min-height: 100vh; width: 100%; display: flex; gap: 20px;">

    <!-- 左侧患者列表 -->
    <div class="patient-list" style="width: 300px; background: white; border-radius: 8px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); overflow-y: auto;">
      <div style="display: flex; gap: 10px; margin-bottom: 16px;">
        <el-input v-model="searchKey" placeholder="身份证/医保卡/就诊号" clearable size="small" />
        <el-date-picker v-model="selectedDate" type="date" placeholder="选择日期" format="YYYY/MM/DD" value-format="YYYY/MM/DD" size="small" />
      </div>

      <el-table :data="filteredPatients" stripe style="width: 100%" @row-click="selectPatient" :row-style="{ cursor: 'pointer' }">
        <el-table-column prop="recordId" label="就诊号" width="80" />
        <el-table-column prop="recordName" label="姓名" width="80" />
        <el-table-column prop="recordSex" label="性别" width="60" />
        <el-table-column prop="recordIdcard" label="证件号" />
      </el-table>
    </div>

    <!-- 右侧体检表单 -->
    <div class="exam-form" style="flex: 1; background: white; border-radius: 8px; padding: 30px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); overflow-y: auto;">

      <!-- 患者信息头部 -->
      <div v-if="currentPatient" style="display: flex; align-items: center; gap: 30px; padding-bottom: 25px; border-bottom: 2px solid #ebeef5; margin-bottom: 25px;">
        <el-avatar :size="60" :src="avatarUrl" />
        <div style="flex: 1;">
          <div style="font-size: 20px; font-weight: bold; margin-bottom: 8px;">
            {{ currentPatient.recordName }}
            <span style="font-size: 14px; color: #666;">
              {{ currentPatient.recordSex }} | {{ currentPatient.recordAge }}岁 | 就诊号：{{ currentPatient.recordId }}
            </span>
          </div>
          <div style="display: flex; gap: 20px; font-size: 13px; color: #666; flex-wrap: wrap;">
            <span>医保类型：职工医疗</span>
            <span>联系电话：15509097890</span>
            <span>身份证号：{{ currentPatient.recordIdcard }}</span>
            <span>家庭住址：xx市xx区xx街道</span>
          </div>
        </div>
        <div style="display: flex; gap: 10px;">
          <el-tag type="danger">高血压</el-tag>
          <el-tag type="warning">2型糖尿病</el-tag>
        </div>
      </div>

      <!-- 体征检查 -->
      <div style="margin-bottom: 40px;">
        <h3 style="border-bottom: 2px solid #409eff; padding-bottom: 8px; margin-bottom: 20px; font-size: 18px; color: #333;">体征检查</h3>

        <!-- 身高体重 -->
        <div style="display: flex; gap: 30px; align-items: center; margin-bottom: 30px;">
          <div style="display: flex; align-items: center; gap: 10px;">
            <span style="font-size: 14px; color: #333;">身高</span>
            <el-input-number
              v-model="height"
              :min="0"
              :max="250"
              controls-position="right"
              size="small"
              style="width: 140px;"
            />
            <span style="font-size: 14px; color: #666;">CM</span>
          </div>
          <div style="display: flex; align-items: center; gap: 10px;">
            <span style="font-size: 14px; color: #333;">体重</span>
            <el-input-number
              v-model="weight"
              :min="0"
              :max="300"
              controls-position="right"
              size="small"
              style="width: 140px;"
            />
            <span style="font-size: 14px; color: #666;">KG</span>
          </div>
          <div style="display: flex; align-items: center; gap: 10px;">
            <span style="font-size: 14px; color: #333;">BMI</span>
            <el-input-number
              v-model="bmi"
              :min="0"
              :max="100"
              controls-position="right"
              disabled
              size="small"
              style="width: 140px;"
            />
            <span style="font-size: 14px; color: #666;">kg/m²</span>
          </div>
        </div>

        <!-- 血压测量 -->
        <div style="margin-bottom: 30px;">
          <div style="display: flex; align-items: center; gap: 15px; margin-bottom: 15px;">
            <span style="font-size: 14px; color: #333;">血压测量(收缩压/舒张压)</span>
            <el-button size="small" @click="addBloodPressure">+</el-button>
          </div>
          <div style="display: flex; gap: 30px; margin-top: 15px;">
            <div>
              <span style="font-size: 14px; color: #333;">部位</span>
              <el-select
                v-model="bpLocation"
                size="small"
                style="width: 140px; margin-left: 15px;"
              >
                <el-option label="右手臂" value="rightArm" />
                <el-option label="左手臂" value="leftArm" />
              </el-select>
            </div>
          </div>

          <!-- 三次测量 -->
          <div style="display: flex; gap: 40px; margin-top: 20px; flex-wrap: wrap;">
            <div v-for="(item, index) in bloodPressures" :key="index" style="display: flex; align-items: center; gap: 10px;">
              <span style="font-size: 14px; color: #333;">第{{ ['一', '二', '三'][index] }}次</span>
              <el-input-number
                v-model="item.systolic"
                :min="0"
                :max="300"
                controls-position="right"
                size="small"
                style="width: 100px;"
              />
              <span style="font-size: 14px; color: #666;">/</span>
              <el-input-number
                v-model="item.diastolic"
                :min="0"
                :max="200"
                controls-position="right"
                size="small"
                style="width: 100px;"
              />
              <span style="font-size: 14px; color: #666;">mmHg</span>
            </div>
          </div>

          <!-- 平均值 -->
          <div style="display: flex; align-items: center; gap: 10px; margin-top: 25px;">
            <span style="font-size: 14px; color: #333;">平均值</span>
            <el-input-number
              v-model="avgSystolic"
              :min="0"
              :max="300"
              controls-position="right"
              disabled
              size="small"
              style="width: 100px;"
            />
            <span style="font-size: 14px; color: #666;">/</span>
            <el-input-number
              v-model="avgDiastolic"
              :min="0"
              :max="200"
              controls-position="right"
              disabled
              size="small"
              style="width: 100px;"
            />
            <span style="font-size: 14px; color: #666;">mmHg</span>
          </div>
        </div>
      </div>

      <!-- 辅检项目 -->
      <div style="margin-bottom: 40px;">
        <h3 style="border-bottom: 2px solid #409eff; padding-bottom: 8px; margin-bottom: 20px; font-size: 18px; color: #333;">辅检项目</h3>

        <!-- 血糖测量 -->
        <div style="display: flex; gap: 50px; margin-bottom: 30px; flex-wrap: wrap;">
          <div>
            <span style="font-size: 14px; color: #333;">空腹血糖</span>
            <el-input-number
              v-model="fastingGlucose"
              :min="0"
              :max="30"
              controls-position="right"
              size="small"
              style="width: 140px; margin-left: 15px;"
            />
            <span style="font-size: 14px; color: #666;">mmol/L</span>
          </div>
          <div>
            <span style="font-size: 14px; color: #333;">餐后2小时血糖</span>
            <el-input-number
              v-model="postprandialGlucose"
              :min="0"
              :max="30"
              controls-position="right"
              size="small"
              style="width: 140px; margin-left: 15px;"
            />
            <span style="font-size: 14px; color: #666;">mmol/L</span>
          </div>
        </div>
      </div>

      <!-- 底部按钮 -->
      <div style="text-align: right; margin-top: 40px;">
        <el-button type="primary" plain @click="startCollect">开始采集</el-button>
        <el-button type="success" @click="saveResult">保存结果</el-button>
      </div>

    </div>

  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 原始患者数据
const allPatients = ref([])
// 过滤后的患者数据（用于表格）
const filteredPatients = ref([])
// 搜索关键词
const searchKey = ref('')
// 选中日期（暂未用于过滤）
const selectedDate = ref('2025/10/25')
// 当前选中患者
const currentPatient = ref(null)

// 头像
const avatarUrl = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 获取患者列表
const fetchPatients = async () => {
  try {
    const response = await axios.get('http://localhost:5108/api/Manager/IndexcollectionShow')
    // 确保数据是数组
    allPatients.value = Array.isArray(response.data.data) ? response.data.data : []
    applyFilter() // 初始加载后过滤（此时 searchKey 为空，显示全部）
  } catch (error) {
    ElMessage.error('加载患者列表失败')
    console.error('请求错误:', error)
  }
}

// 本地过滤（不发请求）
const applyFilter = () => {
  const keyword = searchKey.value.trim().toLowerCase()
  if (!keyword) {
    filteredPatients.value = [...allPatients.value]
    return
  }

  filteredPatients.value = allPatients.value.filter((patient) => {
    return (
      (patient.recordId && patient.recordId.toLowerCase().includes(keyword)) ||
      (patient.recordName && patient.recordName.toLowerCase().includes(keyword)) ||
      (patient.recordIdcard && patient.recordIdcard.toLowerCase().includes(keyword))
    )
  })
}

// 监听搜索关键词变化
watch(searchKey, applyFilter)

// 页面加载时获取数据
onMounted(() => {
  fetchPatients()
})

// 选择患者
const selectPatient = (row) => {
  currentPatient.value = row
}

// === 以下为体检表单逻辑（保持不变）===

const height = ref(null)
const weight = ref(null)
const bmi = computed(() => {
  if (height.value && weight.value) {
    const h = height.value / 100
    return parseFloat((weight.value / (h * h)).toFixed(2))
  }
  return null
})

const bpLocation = ref('rightArm')
const bloodPressures = ref([
  { systolic: null, diastolic: null },
  { systolic: null, diastolic: null },
  { systolic: null, diastolic: null }
])

const avgSystolic = computed(() => {
  const validValues = bloodPressures.value.filter((item) => item.systolic != null)
  if (validValues.length === 0) return null
  const sum = validValues.reduce((acc, item) => acc + item.systolic, 0)
  return Math.round(sum / validValues.length)
})

const avgDiastolic = computed(() => {
  const validValues = bloodPressures.value.filter((item) => item.diastolic != null)
  if (validValues.length === 0) return null
  const sum = validValues.reduce((acc, item) => acc + item.diastolic, 0)
  return Math.round(sum / validValues.length)
})

const fastingGlucose = ref(null)
const postprandialGlucose = ref(null)

const addBloodPressure = () => {
  if (bloodPressures.value.length < 3) {
    bloodPressures.value.push({ systolic: null, diastolic: null })
  }
}

const startCollect = () => {
  ElMessage.info('开始采集...')
}

const saveResult = () => {
  ElMessage.success('保存成功！')
}
</script>

<style scoped>
/* 可选：微调样式 */
</style>